/*
 * MsgWindow.java
 *
 * Created on 2008年10月27日, 下午2:41
 */

package ipmsg.gui;

import ipmsg.etc.Command;
import ipmsg.etc.GlobalConstant;
import ipmsg.etc.UtilityGlobal;
import ipmsg.etc.GlobalVar;
import ipmsg.network.UtilityNet;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;
import javax.swing.JScrollBar;

/**
 *
 * @author  Noeru
 */
public class MsgWindow extends javax.swing.JFrame implements KeyListener{

    /**
     * 联系人。<br>
     * 为空为广播，长度为1表示私聊。大小大于1表示群发。
     */
    private ArrayList<String> contacts=new ArrayList<String>(); 
    
    /**
     * 窗口表示。<br>
     * 系统通过key标示窗口并记录。以保证某些窗口只有一个实例。<br>
     * 群发窗口不存储。因为key为null。
     */
    private String key;
    
    /**
     * 插入格式化代码
     */
    InsertFormatText ift;
    
    
    /** Creates new form MsgWindow */
    public MsgWindow(ArrayList<String> contacts) {
        this.init(contacts);
    }
    
    /**
     * 初始化单人聊天和广播。
     * @param to 发送方的ip ,如果为空，则表示广播
     * @param msgContent  初始化消息内容
     * @param from  消息来源,一般情况下不会用到，在广播的情况下记录发送者的ip
     */
    public MsgWindow(String to,String msgContent,String from){
        if(to==null)this.init(null);
        else{
            ArrayList<String> tmp = new ArrayList<String>();
            tmp.add(to);
            this.init(tmp);
        }
        //如果不为空，则表示初始化包含消息append.
        if(msgContent!=null)
            this.appendNewMsg(msgContent, from);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jPanel3 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        guiContent = new javax.swing.JTextPane();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        guiWtsay = new javax.swing.JTextArea();
        GUI_fontName = new javax.swing.JComboBox();
        GUI_fontSize = new javax.swing.JComboBox();
        GUI_fontStyle = new javax.swing.JComboBox();
        GUI_fontColor = new javax.swing.JComboBox();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        guiTips = new javax.swing.JLabel();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenu2 = new javax.swing.JMenu();

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        jPanel1.setLayout(new java.awt.BorderLayout());

        guiContent.setEditable(false);
        jScrollPane1.setViewportView(guiContent);

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 433, Short.MAX_VALUE)
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 227, Short.MAX_VALUE)
        );

        jPanel1.add(jPanel3, java.awt.BorderLayout.CENTER);

        guiWtsay.setColumns(20);
        guiWtsay.setRows(5);
        jScrollPane2.setViewportView(guiWtsay);

        GUI_fontName.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "宋体", "黑体", "Dialog", "Gulim" }));

        GUI_fontSize.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "14", "18", "22", "30", "36", "42" }));

        GUI_fontStyle.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "常规", "斜体", "粗体", "粗斜体" }));

        GUI_fontColor.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "黑色", "红色", "蓝色", "黄色", "绿色" }));

        jButton1.setText("发送");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("取消");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton3.setText("清空");

        guiTips.setText(" ");

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(GUI_fontName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(GUI_fontSize, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(GUI_fontStyle, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(GUI_fontColor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap(193, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                        .addComponent(guiTips, javax.swing.GroupLayout.DEFAULT_SIZE, 201, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jButton3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton1)
                        .addGap(29, 29, 29))))
            .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 433, Short.MAX_VALUE)
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(GUI_fontName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(GUI_fontSize, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(GUI_fontStyle, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(GUI_fontColor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(8, 8, 8)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton2)
                    .addComponent(jButton3)
                    .addComponent(guiTips))
                .addContainerGap(12, Short.MAX_VALUE))
        );

        jPanel1.add(jPanel2, java.awt.BorderLayout.SOUTH);

        jMenu1.setText("File");
        jMenuBar1.add(jMenu1);

        jMenu2.setText("Edit");
        jMenuBar1.add(jMenu2);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 433, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 431, Short.MAX_VALUE)
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-441)/2, (screenSize.height-485)/2, 441, 485);
    }// </editor-fold>//GEN-END:initComponents

private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
// TODO add your handling code here:
    this.exit();
}//GEN-LAST:event_formWindowClosing

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
// TODO add your handling code here:
    this.exit();
}//GEN-LAST:event_jButton2ActionPerformed

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
    this.sendMsg();
}//GEN-LAST:event_jButton1ActionPerformed



    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JComboBox GUI_fontColor;
    private javax.swing.JComboBox GUI_fontName;
    private javax.swing.JComboBox GUI_fontSize;
    private javax.swing.JComboBox GUI_fontStyle;
    private javax.swing.JTextPane guiContent;
    private javax.swing.JLabel guiTips;
    private javax.swing.JTextArea guiWtsay;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    // End of variables declaration//GEN-END:variables
private void init(ArrayList<String> contacts){
        
        initComponents();
        
        ift=new InsertFormatText(this.guiContent);
        //绑定按键
        this.guiWtsay.addKeyListener(this);
        this.guiContent.addKeyListener(this);
        this.GUI_fontColor.addKeyListener(this);
        this.GUI_fontName.addKeyListener(this);
        this.GUI_fontSize.addKeyListener(this);
        this.GUI_fontStyle.addKeyListener(this);
        
        this.contacts=contacts;
        if(contacts==null){
            this.key="broadcast";
            this.setTitle("广播");
        }else if(contacts.size()>1){
            this.key=null;
            this.setTitle("群发 ( "+this.contacts.size()+" 个用户 )");
        }else {
            this.key=contacts.get(0);
            //this.setTitle(GlobalVar.getUserName(this.key)+"( "+this.key+" )");
            this.setTitle(GlobalVar.getUser(this.key).getName()
                    +"( "+this.key+" )");
        }
        //注册
        if(key!=null)GlobalVar.addWindow(key, this);
        this.guiWtsay.requestFocus();
    }

    public void keyTyped(KeyEvent e) {
    }

    public void keyPressed(KeyEvent e) {
    }

    public void keyReleased(KeyEvent e) {
        char c = e.getKeyChar();
        int modifiers = e.getModifiers(); 

        if ((GlobalVar.SEND_MSG_STYLE==GlobalConstant.CTRL_ENTER
                &&modifiers==2 & c=='\n')||
                (GlobalVar.SEND_MSG_STYLE==GlobalConstant.ENTER
                &&modifiers==0 & c=='\n')) {
          this.sendMsg();
        }
    }
    
    private void sendMsg(){
        String str=this.guiWtsay.getText().trim();
        if(str.isEmpty()){
            this.guiTips.setText("请输入消息内容！");
            this.guiWtsay.requestFocus();
            return;
        }
        //是否超过长度限制。
        if(str.length()>GlobalConstant.MSG_LEN)
        if(str.length()>1000-
                GlobalVar.USER_NAME.length()-GlobalVar.HOST_NAME.length()){
            
            this.guiTips.setText("一次性发送字符太多！");
            this.guiWtsay.requestFocus();
            return;
        }
            
        
        Command tmpCom = new Command(
                GlobalConstant.IPMSG_SENDMSG|GlobalConstant.IPMSG_SENDCHECKOPT);
        tmpCom.setAdditional(str);
        
  
        //如果是广播，则直接广播
        if(this.key!=null&&this.key.equals("broadcast")){
            UtilityNet.broadcastUdpPacket(tmpCom);
        }
        //如果是群，则使用点对点方式给群里面的每一位用户发送消息
        else {
            this.appendNewMsg(str, null);
            for(int count=0;count<this.contacts.size();count++){
                if(!GlobalVar.ALL_IP_ADDRESS.contains(this.contacts.get(count))){
                    tmpCom.setIp(this.contacts.get(count));
                    UtilityNet.sendUdpPacket(tmpCom);
                }
            }
        }
        //清空发送版内容
        this.guiWtsay.setText("");
        this.guiWtsay.requestFocus();
        
    }
    
    /**
     * 在后面添加消息。
     * @param msgContent 消息内容
     * @param fromIp 来自。如果为空。则为自己自行添加。
     */
    public void appendNewMsg(String msgContent,String from){
        //确定昵称
        String name=(from==null)?"自己":GlobalVar.getUser(from).getName();
        //插入标题
        ift.insertFormatText(UtilityGlobal.getTime()+" "+name+GlobalVar.NEW_LINE
                , "黑体", "粗体", 14, "蓝色");
        
        //确定字体格式
        String fonts = (String) this.GUI_fontName.getSelectedItem();
        String style = (String) this.GUI_fontStyle.getSelectedItem();
        int size = Integer.parseInt((String) 
                this.GUI_fontSize.getSelectedItem());
        String color = (String) this.GUI_fontColor.getSelectedItem();
        //插入内容
        ift.insertFormatText(msgContent+
                GlobalVar.NEW_LINE+GlobalVar.NEW_LINE
                , fonts, style, size, color);
        
        JScrollBar jb = this.jScrollPane1.getVerticalScrollBar();
        jb.setValue(jb.getMaximum());
    }
    
    private void exit(){
        if(this.key!=null)GlobalVar.delWindow(key);
        this.dispose();
    }
}
